package com.kinon.ceshiaccount.fragment.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.ceshiaccount.R;
import com.kinon.ceshiaccount.activity.OrderPayActivity;
import com.kinon.ceshiaccount.adapter.DiningTypeAdapter;
import com.kinon.ceshiaccount.adapter.SettlementAdapter;
import com.kinon.ceshiaccount.application.AccountApplication;
import com.kinon.ceshiaccount.bean.RoleBean;
import com.kinon.ceshiaccount.bean.base.BaseBean;
import com.kinon.ceshiaccount.constant.Constant;
import com.kinon.ceshiaccount.fragment.BaseFragment;
import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.network.MyCallback;
import com.kinon.ceshiaccount.util.LoadDialogManager;
import com.kinon.ceshiaccount.util.MyDecimalFormat;
import com.kinon.ceshiaccount.util.SPManage;
import com.kinon.ceshiaccount.view.computer.ComputerNumView;
import com.kinon.ceshiaccount.wxpay.WxOrderPayActivity;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by luohao on 2017-06-16.
 * 结算页面，负责金额计算生成结算订单
 */

public class WxpayFragment extends BaseFragment implements
        ComputerNumView.OnComputerListener {
    private View mView;
    /**
     * 结算的总价
     */
    private TextView tv_total;
    /**
     * 显示就餐类型的布局
     */
    private RelativeLayout rl_select;
    /**
     * 输入的金额
     */
    private EditText et_money;
    /**
     * 计算记录的集合
     */
    private ListView list_money;
    /**
     * 计算机
     */
    private ComputerNumView cview_settlement;
    /**
     * 选择就餐类型
     */
    private GridView grid_diningType;
    /**
     * 加的符号
     */
    private TextView et_Spuls;
    /**
     * 表示输入的数字
     */
    private String etNum = "";
    private ArrayList<String> moneyList = new ArrayList<>();
    private SettlementAdapter adapter = null;
    /**
     * 不包括输入框里的总价
     */
    private Double totalMoney = 0.0;
    /**
     * 显示的总价
     */
    private Double showTotalMoney = 0.0;

    private Context context;
    private int type = 0;
    private TextWatcher watcher = new TextWatcher() {
        //text  输入框中改变前的字符串信息  start 输入框中改变前的字符串的起始位置
        //count 输入框中改变前后的字符串改变数量一般为0 after 输入框中改变后的字符串与起始位置的偏移量
        @Override
        public void beforeTextChanged(CharSequence text, int start, int icount, int iafter) {

        }

        //text  输入框中改变后的字符串信息 start 输入框中改变后的字符串的起始位置
        // count输入框中改变前的字符串的位置 默认为0 after 输入框中改变后的一共输入字符串的数量
        @Override
        public void onTextChanged(CharSequence text, int start, int icount, int iafter) {

        }

        //editable  输入结束呈现在输入框中的信息
        @Override
        public void afterTextChanged(Editable editable) {
            double price = 0.0;
            if (editable.length() == 0) {
                price = 0.0;
            } else if (editable.toString().trim().equals(".")) {
                return;
            } else {
                price = Double.parseDouble(editable.toString().trim());
            }
            showTotalMoney = totalMoney + price;
            String strShowMoney = String.valueOf(showTotalMoney);
            if (strShowMoney.length() > 10) {
                strShowMoney = MyDecimalFormat.dFormat(showTotalMoney);
            }
            tv_total.setText(strShowMoney);
//            totalMoney=Double.parseDouble(editable.toString().trim());
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_settlement_layout, container, false);
        return mView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        context = AccountApplication.getInstance();
        tv_total = (TextView) mView.findViewById(R.id.tv_total);
        et_money = (EditText) mView.findViewById(R.id.et_money);
        list_money = (ListView) mView.findViewById(R.id.list_money);
        cview_settlement = (ComputerNumView) mView.findViewById(R.id.cview_settlement);
        grid_diningType = (GridView) mView.findViewById(R.id.grid_diningType);
        rl_select = (RelativeLayout) mView.findViewById(R.id.rl_select);

        et_Spuls = (TextView) mView.findViewById(R.id.et_Spuls);
        et_money.addTextChangedListener(watcher);

        cview_settlement.setOnComputerListener(this);
        adapter = new SettlementAdapter(getActivity(), moneyList);
        list_money.setAdapter(adapter);

        showDiningType();
//        cview_settlement
    }

    private void showDiningType() {
        String roles = SPManage.getInstance().getString("roles");
        if (TextUtils.isEmpty(roles)) {
            return;
        }
//        Log.e("lh", "roles== "+roles );
        Gson gson = new Gson();
        final ArrayList<RoleBean> binings = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(roles);
            for (int i = 0; i < array.length(); i++) {
                RoleBean bean = gson.fromJson(array.get(i).toString(), RoleBean.class);
                binings.add(bean);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (binings.size() == 0) {
            rl_select.setVisibility(View.GONE);
            return;
        }
        type = binings.get(0).getId();
        if (binings.size() == 1) {
            rl_select.setVisibility(View.GONE);
        }
        grid_diningType.setNumColumns(binings.size());
        final DiningTypeAdapter diningAdapter = new DiningTypeAdapter(context, binings);
        grid_diningType.setAdapter(diningAdapter);
        grid_diningType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                type = binings.get(i).getId();
                diningAdapter.selectItem(i);
                diningAdapter.notifyDataSetChanged();
            }
        });

    }

    /**
     * 计算器的点击监听事件
     *
     * @param num
     */
    @Override
    public void onComputerListener(String num) {
        numCount(num);
    }

    /**
     * 计算器的运算
     *
     * @param num 返回的键对应的string
     */
    private void numCount(String num) {
        //p代表.
        if (num.equals("p")) {
            //小数点的计算
            counPoint();
        }
        //j代表加
        else if (num.equals("j")) {
            //加号计算
            countPlus();
        }
        //c代表清除
        else if (num.equals("c")) {
            //清除计算
            countClear();
        }
        //o代表完成
        else if (num.equals("o")) {
            //判断是否是紧急状态
            if (!Constant.URGENT_TYPE) {
                saveorder();
            } else {
                urgentJiesuan();
            }

        }
        //d代表删除上一个
        else if (num.equals("d")) {
            //删除上一个
            countDelete();
        }
        //除了上面几种特殊键就是数字键
        else {
            if (etNum.length() >= 7) {
                return;
            }
            etNum += num;
            et_money.setText(etNum);
        }
    }

    /**
     * 小数点的计算
     */
    private void counPoint() {
        //判断etNum中是否已经存在.
        if (etNum.contains(".")) {
            return;
        } else {
            etNum += ".";
            et_money.setText(etNum);
        }
    }

    private void saveorder() {
        LoadDialogManager.gerInstnce().showProgressDialog
                (getContext(), "订单生成中...");
        Call<BaseBean<String>> call = HttpManage.getRequestApi().saveNewOrder(
                SPManage.getInstance().getToken(), showTotalMoney + "", type + "", "");
        call.enqueue(new MyCallback<BaseBean<String>>() {
            @Override
            public void onSuccess(Call<BaseBean<String>> call, Response<BaseBean<String>> response) {
                LoadDialogManager.gerInstnce().dismissProgressDialog();
                BaseBean<String> base = response.body();
                Intent intent = new Intent(getActivity(), WxOrderPayActivity.class);
                intent.putExtra("total", tv_total.getText().toString().trim());
                intent.putExtra("diningType", type);
                intent.putExtra("oridrid", base.getData());
                startActivity(intent);
                //完成跳转然后清空数据
                countClear();
            }

            @Override
            public void onError(int code, String error) {
                LoadDialogManager.gerInstnce().dismissProgressDialog();
                Toast.makeText(context, error, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 紧急结算
     */
    private void urgentJiesuan() {
        Intent intent = new Intent(getContext(), OrderPayActivity.class);
        intent.putExtra("total", tv_total.getText().toString().trim());
        intent.putExtra("diningType", type);
        startActivity(intent);
        //完成跳转然后清空数据
        countClear();
    }

    /**
     * 清除计算
     */
    private void countClear() {
        et_Spuls.setVisibility(View.GONE);
        etNum = "";
        totalMoney = 0.0;
        showTotalMoney = 0.0;
        tv_total.setText(totalMoney + "");
        et_money.setText(etNum);
        //清空集合
        moneyList.clear();
        adapter.notifyDataSetChanged();
    }

    /**
     * 加号计算
     */
    private void countPlus() {
        //判断输入框里是否有值 否直接跳出判断
        if (TextUtils.isEmpty(etNum)) {
            return;
        }
        //判断是否是第一次
        if (moneyList.size() == 0) {
            et_Spuls.setVisibility(View.VISIBLE);
            totalMoney = showTotalMoney;
            moneyList.add(etNum);
            etNum = "";
            et_money.setText(etNum);
            adapter.notifyDataSetChanged();
            return;
        }
        //判断加号是否显示，显示直接加入集合不显示先显示
        if (et_Spuls.getVisibility() == View.VISIBLE) {
//                 et_Spuls.setVisibility(View.VISIBLE);
            totalMoney = showTotalMoney;
            moneyList.add("+" + etNum);
            etNum = "";
            et_money.setText(etNum);
            adapter.notifyDataSetChanged();
        } else {
            et_Spuls.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 删除上一个
     */
    private void countDelete() {
        if (etNum.trim().length() > 0) {
            etNum = etNum.substring(0, etNum.length() - 1);
            et_money.setText(etNum);
        } else {
            et_Spuls.setVisibility(View.GONE);
            if (moneyList.size() == 0) {
                return;
            }
            //得到list集合的最后一个字符
            String reNum = moneyList.get(moneyList.size() - 1);
            //判断字符中是否有+的符号
            if (reNum.contains("+")) {
                etNum = reNum.substring(1);
                et_money.setText(etNum);
                et_Spuls.setVisibility(View.VISIBLE);
            } else {
                et_Spuls.setVisibility(View.GONE);
                etNum = reNum;
                et_money.setText(etNum);
            }
            showTotalMoney = showTotalMoney - (Double.parseDouble(reNum.trim()));

            totalMoney = totalMoney - (Double.parseDouble(reNum.trim()));

            String strShowMoney = String.valueOf(showTotalMoney);
            if (strShowMoney.length() > 10) {
                strShowMoney = MyDecimalFormat.dFormat(showTotalMoney);
            }
            tv_total.setText(strShowMoney);

//            tv_total.setText(showTotalMoney+"");
            moneyList.remove(moneyList.size() - 1);
            adapter.notifyDataSetChanged();
        }
    }
}
